<?php
namespace App\Models;

use App\Models\Model;
use App\Models\System\User;
use App\Models\Teaching\HomeworkInfo;
use App\Models\Teaching\TeachingSign;
use App\Models\Teaching\TeachingSubject;
use App\Models\Traits\HasManyFiles;

class Participant extends Model
{
    use HasManyFiles;
    protected $table = 'participant';
    protected $guarded = [];
    protected $hidden = [
        'created_at',
        'updated_at'
    ];
    protected $appends = [
        'teaching_info'
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function sign()
    {
        return $this->hasOne(TeachingSign::class, 'user_id', 'user_id')->where('status', 1);
    }

    public function homework()
    {
        return $this->hasMany(HomeworkInfo::class, 'user_id', 'user_id')->orderBy('created_at', 'desc');
    }

    public function creator()
    {
        return $this->hasOne(User::class, 'id', 'creator_id');
    }
    public function teachingSubject()
    {
        return $this->hasMany(TeachingSubject::class, 'user_id', 'user_id')->where('deleted', 0);
    }

    public function getTeachingInfoAttribute(){
        $teachingData = !empty($this->relations['teachingSubject']) ? $this->relations['teachingSubject'] : '';

        if(!$teachingData){
            return [];
        }

        $subjectList = [];
        $classList = [];
        foreach($teachingData as $t) {
            $subjectList[] = $t->subject_set ? $t->subject_set[0]['selectValue'] : '';
            $classList[] = $t->grade_set ? $t->grade_set['grades'].$t->class_set['classes'] : '';
        }

        $result = [
            'subjects' => !empty($subjectList) ? implode(', ', collect($subjectList)->unique()->toArray()) : "-",
            'classes' => !empty($classList) ? implode(', ', $classList) : "-"
        ];

        return $result;
    }

    public function setFilesIdAttribute($filesIdArr)
    {
        $this->files()->whereNotIn('id', $filesIdArr)->update(['ilk_type' => null, 'ilk_id' => null]);
        $this->files()->saveMany(Files::query()->whereIn('id', $filesIdArr)->get());
    }
}
?>
